<?php
namespace  controllers;
use controllers\api;
use SMB\Goods\product;
use SMB\Goods\goods;
use SMB\Goods\product_class;
use SMB\Goods\supplier;
use SMB\Goods\supplier_goods_relation;
use Model\suppliers;
use SMB\Statistics\shop_sales_statistics;
use Model\shop;
use controllers\statistics;
use Model\supplier_log;
use Model\notice;

class products extends api{
    public function __where(){
        $where = array();
        //接收所选商品的状态
        if(isset($_REQUEST['status'])){
            if(!empty($_REQUEST['status'])){
                $where['product_type'] = (int)$_REQUEST['status'];
            }
        }
        if(isset($_REQUEST['product_title'])){
            if(!empty($_REQUEST['product_title'])){
                $where['product_title']['$regex'] = $_REQUEST['product_title'];
            }
        }
        //接收所选类目
        if(isset($_REQUEST['classification_id'])){
            if(!empty($_REQUEST['classification_id'])){
                $where['product_class_id'] = new \MongoId($_REQUEST['classification_id']);
            }
        }
        return $where;
    }
    //商品查看
    public function product_show(){
        $where = $this->__where();
        $where_arr = array();
        $page = 0;
        $limit = 10;

        //接收当前页数
        if(isset($_REQUEST['page'])){
            if(!empty($_REQUEST['page'])){
                $page = $_REQUEST['page'];
            }

        }
        //接收所选店铺
        if(isset($_REQUEST['shop_id'])){
            if(!empty($_REQUEST['shop_id'])){
                $where_arr['shop_id'] = new \MongoId($_REQUEST['shop_id']);
            }
        }
        //状态标识
        $product_type = array('1'=>'正常','2'=>'新品','9'=>'淘汰','10'=>'清仓','11'=>'赠品');


        //查询商品基本信息
        $goods_db = new goods();
        $goods_list = array();
        $goods_arr = $goods_db->find($where,array('product_class_id_arr','sku_id','product_title','product_pic','specification_arr','last_price','price','product_type'));
        foreach ($goods_arr as $v){
            $goods_list[$v['sku_id']] = $v;
        }

        //查询所有店铺
        $shop_db = new shop();
        $shop_list = $shop_db->get_shop();



        // 查询供货商信息
        $supplier_model = new suppliers();
        $supplier_info = $supplier_model->get_sup_info();

        //查询该供货商的商品
        $supplier_relation_model = new supplier_goods_relation();
        $querys = array('supplier_id' => $supplier_info['_id']);
        $filer = array('sku_id','exchange_policy','donation');
        $relation = $supplier_relation_model->find($querys, $filer);

        //查询供应商采购报价
        $batch_list = $supplier_relation_model->find();
        $batch_arr = array();
        foreach ($batch_list as $v){
            $batch_arr[$v['sku_id'].$v['supplier_id'].''][] = $v;
        }
        //查询商品的库存
        $product_model = new product();
        $goods = $product_model->find($where_arr,array('stocks','month_avg_sales','sku_id'));

        //查询库存
        $products = array();
        foreach ($goods as $v) {
            $products[$v['sku_id']] = $v;
        }


        //周销量
        $shop_sales_statistics_model = new shop_sales_statistics();
        $time = date('Ymd', (time() - 86400 * 6));
        $statistics_model = new statistics();
        $shop_sales_statistics_list =  $statistics_model->get_sale($shop_sales_statistics_model,$time);
        $weekly_sale = 0;
        $shop_sales_statistics_arr = array();
        foreach ($shop_sales_statistics_list['result'] as $shop_sales) {
            $shop_sales_statistics_arr['sku_id'] = $shop_sales['sales_money'];
        }
        foreach ($relation as $v) {
            if (isset($shop_sales_statistics_arr[$v['sku_id']])) {
                $weekly_sale += $shop_sales_statistics_arr[$v['sku_id']];
            }
        }
        //获取供应商提供的类目
        $category_array = $this->get_category();
        $class_arr = array();
        $category_arr = array();
        $category_arr_all = array();
        foreach ($relation as $v) {
            if(!isset($goods_list[$v['sku_id']]['product_class_id_arr'])){
                continue;
            }
            $class_arr[$goods_list[$v['sku_id']]['product_class_id_arr'][1].""][$goods_list[$v['sku_id']]['product_class_id_arr'][0].""]= 1;
        }
        foreach ($class_arr as $k=>$v) {
            $category_arr_all = array();
            foreach ($v as $key => $value) {
                $category_arr_all['lists'][] = array('id' => $key, 'text' => $category_array[$key . '']['name']);
            }
            $category_arr_all['text'] = $category_array[$k . '']['name'];
            array_push($category_arr, $category_arr_all);
        }
        //重组数据
        $data_arr = array();
        $data = array();
        //$a = 0;
        foreach ($relation as $v) {
            if(!isset($goods_list[$v['sku_id']])){
                continue;
            }
            if(!empty($where_arr)){
                if(!isset($products[$v['sku_id']])){
                    continue;
                }
            }
            $data_arr['product_title'] = @$goods_list[$v['sku_id']]['product_title'];
            $data_arr['product_pic'] = str_replace('img.ismbao.com','weixin.ismbao.com/tb/140x140/',@$goods_list[$v['sku_id']]['product_pic']);
            $data_arr['specification_arr'] = array();
            $arr = array();
            if(isset($goods_list[$v['sku_id']])){
                foreach ($batch_arr[$v['sku_id'].$supplier_info['_id'].''] as $value) {
                    $specification_list['specification'] = '('.$value['purchase_specification']['purchase_num'].$value['purchase_specification']['units_specification'].')';
                    $specification_list['units'] = $value['purchase_specification']['specification'];
                    $arr[] = $specification_list['last_price'] = $value['sup_price']/100;
                    $specification_list['price'] = '';
                    $specification_list['sign'] = 0;
                    $specification_list['product_pic'] = 'http://weixin.ismbao.com/tb/140x140/tb/140x140/upload/201610/22/1477129969570610.jpg';
                    array_push($data_arr['specification_arr'], $specification_list);
                }
                $specification_list = array();
                foreach ($goods_list[$v['sku_id']]['specification_arr'] as $vv) {
                    if($vv['units'] == 1){
                        $specification_list['product_pic'] = str_replace('img.ismbao.com', 'weixin.ismbao.com/tb/140x140/', $vv['product_pic']);
                        $specification_list['price'] = $vv['price'] / 100;
                        $specification_list['specification'] = $vv['specification'];
                        $specification_list['units'] = 1;
                        $specification_list['last_price'] = '';
                        $specification_list['sign'] = 1;
                        array_push($data_arr['specification_arr'], $specification_list);
                    }
                }
            }
             $data_arr['last_price'] = $arr[0];
             $data_arr['price'] = '';
            $data_arr['stocks'] = $products[$v['sku_id']]['stocks'];
            $data_arr['product_type'] = $product_type[$goods_list[$v['sku_id']]['product_type']];
            $data_arr['weekly_turn'] = isset($products[$v['sku_id']]['month_avg_sales'])?$products[$v['sku_id']]['stocks']/$products[$v['sku_id']]['month_avg_sales']:'未知';
           // $data_arr['last_price'] = @$goods_list[$v['sku_id']]['last_price']/100;
            $data_arr['weekly_sales'] = $weekly_sale;
            $data_arr['sku_id'] = $v['sku_id'];
            $exchange_policy = isset($v['exchange_policy'])?'可退换':'';
            $donation = isset($v['donation'])?$v['donation']:'';
            $data_arr['policy'] = array($exchange_policy,$donation);
            array_push($data, $data_arr);
        }
        $all_num = round(count($data)/$limit);
        $data_list = array_slice($data,$page,$limit);
        //var_dump($data_list);exit;
        $this->success($data_list, $shop_list,$all_num,$category_arr);

    }
    //调价申请
    public function do_price(){
//
        $items = $_POST['item']?$_POST['item']:'';
        $file = $_FILES['file'];//得到传输的数据
        //得到文件名称
        $name = $file['name'];
        $type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型，并且都转化成小写
        $allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型
        //判断文件类型是否被允许上传
        if(!in_array($type, $allow_type)){
            //如果不被允许，则直接停止程序运行
            $this->error('不是图片类型');
        }
        $upload_path = $_SERVER['DOCUMENT_ROOT']."/Public/uploadfile"; //上传文件的存放路径

        if(is_dir($upload_path)){
            move_uploaded_file($file['tmp_name'],$upload_path."/".$file['name']);
        }else{
            $this->error('图片上传失败');
        }

        if(is_dir($upload_path)){
            move_uploaded_file($file['tmp_name'],$upload_path."/".$file['name']);
        }else{
            $this->error('图片上传失败');
        }



        $item = json_decode($items);
        $supplier_model = new suppliers();
        $supplier_info = $supplier_model->get_sup_info();
        $goods_sup_rel_model = new supplier_goods_relation();


        $item_arr = array();
        $category = $item->category;
        $item_arr['voucher'] = "/Public/uploadfile/".$file['name'];
        $item_arr['is_throw'] = 0;
        $item_arr['supplier_name'] = $supplier_info['supplier_name'];
        $item_arr['supplier_id'] = (string)$supplier_info['_id'];
        $change = array();
        foreach ($category as $v){
            $_id = $v->_id;
            $item_arr['last_price'] = $v->last_price;
            $item_arr['specification'] = $v->specification;
            $change['change'] = $item_arr;
            $res = $goods_sup_rel_model->update(array('_id'=>new \MongoId($_id)),array('$set'=>$change));
        }
        if($res['ok']){
            $supplier_log_model = new supplier_log();
            $result1 = $supplier_log_model->add($supplier_info['supplier_name'],$supplier_info['_id'],'申请调价，商品sku_id为','',$item->sku_id);
            if($result1){
               $notice_model = new notice();
               $result2 = $notice_model->add('申请调价,商品的sku_id为：'.$item->sku_id,$supplier_info['supplier_name'],$supplier_info['_id'],'','admin',$item->sku_id);
                if($result2){
                    $this->success('成功');
                }
            }
        }

//        if($res['ok']){
//            echo '成功';
//        }
//        $supplier_journal_db = new supplier_journal();
//        //查询供货商信息
//        $supplier = $this->get_supplier('15723095049');
//        $data['create_name'] = $supplier['supplier_name'];
//        $data['create_time'] = time();
//        $data['describe'] = '申请调价商品xxx';
    }
    //调价详情
    public function change_price_show(){
        // 查询供货商信息
        $suppler_model = new suppliers();
        $supplier_relation = new supplier_goods_relation();
        $supplier_info = $suppler_model->get_sup_info();

        //查询所有商品信息
        $goods_db = new goods();
        $goods_list = array();
        $goods_arr = $goods_db->find(array(),array('sku_id','product_title','specification_arr'));
        foreach ($goods_arr as $v){
            $goods_list[$v['sku_id']] = $v;
        }

        //查看供应商所有商品
        $querys = array('supplier_id' => $supplier_info['_id']);
        $filer = array('sku_id');
        $relation = $supplier_relation->find($querys, $filer);

        //查询供应商采购报价
        $batch_list = $supplier_relation->find();
        $batch_arr = array();
        foreach ($batch_list as $v){
            $batch_arr[$v['sku_id'].$v['supplier_id'].''][] = $v;
        }

        //重组数组
        $data = array();
        $data_arr = array();
        foreach ($relation as $v) {
            if(!isset($goods_list[$v['sku_id']])){
                continue;
            }
            $data_arr['product_title'] = @$goods_list[$v['sku_id']]['product_title'];//商品名称
            $data_arr['specification_arr'] = array();
            $specification_list = array();
            if(isset($goods_list[$v['sku_id']])){
                foreach ($batch_arr[$v['sku_id'].$supplier_info['_id'].''] as $value) {
                    $specification_list['specification'] = $value['purchase_specification']['specification'].'('.$value['purchase_specification']['purchase_num'].$value['purchase_specification']['units_specification'].')';
                    $specification_list['last_price'] = $value['sup_price']/100;
                    $specification_list['_id'] = (string)$value['_id'];
                    array_push($data_arr['specification_arr'], $specification_list);
                }
            }
            $data_arr['sku_id'] = $v['sku_id'];
            array_push($data, $data_arr);
        }
        $this->success($data);
    }
    //获取所有类目
    public function get_category(){
        $category_db = new product_class();
        $category_list = $category_db->find();
        $category_array = array();
        foreach ($category_list as $category){
            $category_array[(string)$category['_id']] = $category;
        }
        return $category_array;
    }

    //获取商品所有信息
    public function get_goods_info(){
        $good_db = new goods();
        $goods = $good_db->find();
        $products = array();
        foreach($goods as $v){
            $products[$v['sku_id']] = @$v;
        }
        return $products;
    }

}